const m = require("./md5.js");

var sign = {};

sign.sort = function(data)
{
    var keys = Object.keys(data).sort();
    var result = {};
    for(var i = 0; i < keys.length; i++){
        var key = keys[i];
        result[key] = data[key];
    }
    return result;
}

sign.jsonVAL = function(json)
{
    var v = '';
    for(var i in json){
        v += json[i];
    }
    return v;
}

sign.getTimestamp =function()
{
    return Date.parse(new Date()) / 1000;
}

sign.mtRand = function(min, max)
{
    var result = Math.random() * (max - min + 1) + min;
    return parseInt(result);
}

sign.sign = function(appkey, json)
{
    json.timestamp = sign.getTimestamp();
    json.rand = sign.mtRand(100000, 999999);
    json.appkey = appkey;
    json.sign = m.md5(sign.jsonVAL(sign.sort(json)));
    delete json.appkey;
    return json;
}

module.exports = sign;